package com.qf.petmall.starter.login;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.petmall.starter.login.entity.Users;
import com.qf.petmall.starter.utils.CommonConstants;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

public class CreateTooken {
    public static String createToken(Users user) throws JsonProcessingException {

        final JwtBuilder builder = Jwts.builder();

        final HashMap<String, Object> map = new HashMap<>();

        // user ---> json
        final ObjectMapper objectMapper = new ObjectMapper();
        final String userJson = objectMapper.writeValueAsString(user);

        map.put(CommonConstants.JWT_CLAIMS_KEY,userJson);

        final String jwt = builder.setClaims(map) // 自定义数据
                .setSubject(user.getUsername())
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setIssuer(CommonConstants.JWT_AUTHOR)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                .signWith(SignatureAlgorithm.HS256, CommonConstants.JWT_SECRET_KEY)
                .compact();

        return jwt;
    }

}
